/* eslint-disable prefer-const */
<template>
  <page-header-wrapper>
    <a-row :gutter="24">
      <a-col span="24">
        <a-radio-group v-model="listMajor" @change="()=>{this.getTableData()}" style="margin-right:1%" >
          <a-radio-button value="0">
            <a-icon type="file-search"/> 房建列表
          </a-radio-button>
          <a-radio-button value="1">
            <a-icon type="schedule"></a-icon> 市政列表
          </a-radio-button>
        </a-radio-group>
        <a-button type="primary" style="margin-bottom:15px;margin-right:15px" @click="handleAdd()">新增</a-button>
        <!-- <a-button type="danger" @click="handleDelete()" style="margin-bottom:15px;margin-right:10px;margin-left:15px" :disabled="!hasSelected" :loading="confirmLoading">删除</a-button> -->
        <a-input-search placeholder="输入您要搜索的内容" enter-button @search="onSearch" style="width:15%" v-model="search" />
        <!-- <span class="tips" v-if="hasSelected">{{ `您已选择了${selectedRowKeys.length}项` }}</span> -->
        <keep-alive>
          <a-table
            :columns="columns"
            :data-source="dataSource"
            :rowClassName="rowClassName"
            @change="handleTableChange"
            :pagination="pagination"
            :scroll="{ x: 1200 }"
            :loading="tableLoading"
          >
            <span slot="is_delete" slot-scope="is_delete">
              <a-tag v-if="is_delete===1" color="green">
                正常
              </a-tag>
              <a-tag v-else color="red">
                禁用
              </a-tag>
            </span>
            <template slot="action" slot-scope="text, record">
              <a @click="handleInfo(record)">详情</a>
              <a-divider type="vertical" />
              <a @click="jumpToList(record)">管理</a>
              <a-divider type="vertical" />
              <a-popconfirm
                v-if="dataSource.length"
                title="确定操作?"
                okText="确定"
                cancelText="取消"
                @confirm="() => onDisabled(record,1)"
              >
                <a href="javascript:;" v-if="record.is_delete===1" >禁用</a>
                <a href="javascript:;" v-else >恢复</a>
              </a-popconfirm>
              <a-divider type="vertical" />
              <a-popconfirm
                v-if="dataSource.length"
                title="确定操作?"
                okText="确定"
                cancelText="取消"
                @confirm="() => onDisabled(record,0)"
              >
                <a href="javascript:;" style="color:red">删除</a>
              </a-popconfirm>
            </template>
          </a-table>
        </keep-alive>
      </a-col>
    </a-row>
    <a-modal
      title="操作详情"
      :visible="visible"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
      okText="保存"
      cancelText="取消"
      v-if="visible"
      :maskClosable="false"
    >
      <a-form-model ref="showData" :model="showData" :label-col="{span: 5}" :wrapper-col="{span: 16}" :rules="rules" >
        <a-form-model-item label="大项名称" prop="list_name">
          <a-input v-model="showData.list_name"></a-input>
        </a-form-model-item>
        <a-form-model-item label="评优专业" prop="major" v-if="!status">
          <a-select v-model="showData.major">
            <a-select-option value="0">
              房建
            </a-select-option>
            <a-select-option value="1">
              市政
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="权重" prop="weight">
          <a-input v-model="showData.weight"></a-input>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </page-header-wrapper>
</template>

<script>
import { tableFinds, listCreat, listEdit } from '@/api/liveExamine'
const delay = (function () {
 let timer = 0
 return function (callback, ms) {
  clearTimeout(timer)
  timer = setTimeout(callback, ms)
 }
})()
export default {
  data () {
    return {
      listMajor: '0', // 表格切换 0位房建，1为市政
      tableLoading: false,
      search: '',
      status: Boolean, // 控制模态框为新增或修改，true为修改，false为新增
      // roleList: [],
      selectedRowKeys: [],
      visible: false,
      confirmLoading: false,
      showData: {},
      pagination: {
        current: 1,
        pageSize: 12,
        total: 0,
        showSizeChanger: true,
        pageSizeOptions: ['12', '20', '30', '50']
      },
      columns: [
        // {
        //   title: '序号',
        //   dataIndex: 'index',
        //   key: 'index',
        //   width: '5%'
        // },
        {
          title: '大项名称',
          dataIndex: 'list_name',
          key: 'list_name'
        },
        {
          title: '顺序权重',
          dataIndex: 'weight',
          key: 'weight'
        },
        {
          title: '创建时间',
          dataIndex: 'create_time',
          key: 'create_time'
        },
        {
          title: '创建人',
          dataIndex: 'creator_name',
          key: 'creator_name'
        },
        {
          title: '状态',
          dataIndex: 'is_delete',
          key: 'is_delete',
          scopedSlots: { customRender: 'is_delete' },
          width: '8%'
        },
        {
          title: '操作',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' },
          key: 'action',
          fixed: 'right'
        }
      ],
      dataSource: [],
      rules: {
        list_name: [
          { required: true, message: '内容不可为空', trigger: 'blur' }
        ],
        major: [
          { required: true, message: '内容不可为空', trigger: 'blur' }
        ],
        weight: [
          { required: true, message: '内容不可为空', trigger: 'blur' }
        ]
      },
      rowSelection: {
        onChange: (selectedRowKeys, selectedRows) => {
          var finalRows = selectedRows.map(e => {
            return e.uuid
          })
          this.selectedRowKeys = finalRows
          console.log(this.selectedRowKeys.length)
        },
        onSelect: (record, selected, selectedRows) => {
          // this.selectedRowKeys = record
          // console.log(this.selectedRowKeys)
        }
        // onSelectAll: (selected, selectedRows, changeRows) => {
        //   console.log(selected, selectedRows, changeRows)
        // }
      }
    }
  },
  computed: {
    hasSelected () {
      return this.selectedRowKeys.length > 0
    }
  },
  methods: {
    getTableData (query) {
      // console.log(query)
      this.tableLoading = true
      var fd = new FormData()
      fd.append('per_page', this.pagination.pageSize)
      fd.append('current_page', this.pagination.current)
      if (query) {
        fd.append('query', query)
      }
      // console.log(fd)
      fd.append('list_major', this.listMajor)
      tableFinds(fd).then(res => {
        this.dataSource = res.result.data
        Object.assign(this.pagination, { 'pageSize': Number(res.result.per_page), 'total': res.result.total, 'current': res.result.current_page })
        // console.log(this.pagination)
        this.tableLoading = false
      })
      .catch(err => {
        this.$notification['error']({
          message: 'Error',
          description: err.message
        })
      })
    },
    handleInfo (record) {
      // console.log(record)
      this.status = true
      this.showData = JSON.parse(JSON.stringify(record)) // 深拷贝，防止表格数据被影响
      console.log(this.showData)
      this.visible = true
    },
    rowClassName () {
      return 'rowClass'
    },
    handleCancel () {
      this.showData = { phone: '' }
      this.visible = false
    },
    handleOk () {
      this.$refs.showData.validate(valid => {
        console.log(this.showData)
        if (!valid) {
          return false
        } else {
          this.confirmLoading = true
          if (!this.status) {
            // eslint-disable-next-line eqeqeq
            // if (this.showData.phone == undefined) {
            //   this.showData.phone = ''
            // }
            // eslint-disable-next-line prefer-const
            // let fd = new FormData()
            // fd.append('classic_name', this.showData.classic_name)
            listCreat(this.showData).then(res => {
              // console.log(res.data)
              if (res.code === 200) {
                this.$notification['success']({
                  message: 'Success',
                  description: '添加成功'
                })
                this.getTableData()
                this.visible = false
              } else {
                this.$notification['error']({
                  message: 'Error',
                  description: res.message
                })
              }
            })
            .catch(err => {
              this.$notification['error']({
                message: 'Error',
                description: err.message
              })
            })
          } else {
            // console.log('???????')
            // eslint-disable-next-line prefer-const
            let fd = new FormData()
            fd.append('list_id', this.showData.list_id)
            fd.append('list_name', this.showData.list_name)
            fd.append('weight', this.showData.weight)
            listEdit(fd).then(res => {
              // console.log(res.data)
              if (res.code === 200) {
                this.$notification['success']({
                  message: 'Success',
                  description: '修改成功'
                })
                this.getTableData()
                this.visible = false
              } else {
                this.$notification['error']({
                  message: 'Error',
                  description: res.message
                })
              }
            })
            .catch(err => {
              this.$notification['error']({
                message: 'Error',
                description: err.message
              })
            })
          }
        }
      })
      setTimeout(() => {
        this.confirmLoading = false
      }, 2000)
    },
    handleDelete () {
      this.confirmLoading = true
      setTimeout(() => {
        this.confirmLoading = false
      }, 2000)
    },
    handleAdd () {
      this.status = false
      this.showData = {}
      this.visible = true
    },
    // 分页
    handleTableChange (pagination) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
      this.getTableData(this.search)
    },
    onDisabled (data, action) {
      var fd = new FormData()
      if (action === 0) {
        fd.append('is_delete', 0)
      } else {
        if (data.is_delete === 1) {
          fd.append('is_delete', 2)
        } else {
          fd.append('is_delete', 1)
        }
      }
      fd.append('list_id', data.list_id)
      listEdit(fd).then(res => {
        // console.log(res.data)
        if (res.code === 200) {
          this.$notification['success']({
            message: 'Success',
            description: '操作成功'
          })
          this.getTableData()
        } else {
          this.$notification['error']({
            message: 'Error',
            description: res.message
          })
        }
      }).catch(err => {
          this.$notification['error']({
            message: 'Error',
            description: err.message
          })
      })
    },
    onSearch (value) {
      // console.log(value)
      this.getTableData(value)
    },
    jumpToList (data) {
      this.$store.commit('SET_CURRENTLIST', data) // 将选择的大项信息存放进vuex
      sessionStorage.setItem('list', JSON.stringify(data)) // 存入session防止页面刷新vuex数据丢失
      this.$router.push('/account/listContent')
    }
  },
  watch: {
    search: function (newVal, oldVal) {
      delay(() => {
        this.getTableData(newVal)
      }, 1000)
    }
  },
  created () {
    if (sessionStorage.list) {
      var list = JSON.parse(sessionStorage.list)
      this.listMajor = String(list.list_major) // 从管理页面返回本页面时控制默认打开的表格时房建or市政
    }
    this.getTableData()
  }
}
</script>

<style lang="less" scoped>
/deep/ .rowClass{
  background-color: #fff;
}
/deep/ .ant-table-thead > tr > th {
  background: #fafafa !important;
}
.tips{
  color: red;
}
</style>
